﻿(function ($) {
    "use strict";

    page.createOrRefreshTaskTableBody = function (options) {
        var tbody = getPageContext('tbody');
        if (options != undefined && options.singleRefresh == true) {
            clearPageTimeout(function () {
                options['autoRefresh'] = true;
                options['autoRefreshInterval'] = tbody.data('autoRefreshInterval');
            });
        }
        axiosPost({
            url: "/schedule/task/getAllViewTask",
            success: function (json) {
                debugger;
                var tbodyHtml = '';
                if (json && json.length > 0) {
                    for (var i in json) {
                        if (json.hasOwnProperty(i)) {
                            if (!json[i].id || !json[i].taskId) {
                                page.createOrRefreshTaskTableBody(options);
                                return;
                            }
                            var status = json[i].status;
                            var pauseAction = (status == 'P' || status == 'RP') ? 'play' : 'pause';
                            tbodyHtml = tbodyHtml + '<tr>'
                                + '<td class="selector text-primary"><input name="id" type="hidden" value="' + json[i].id + '"/><span class="text-ellipsis taskId">' + json[i].taskId + '</span></td>'
                                + '<td class="selector"><span class="text-ellipsis">' + json[i].taskName + '</span></td>'
                                + '<td class="selector text-align-center"><span class="translate" translateFor="taskType" translateValue="' + json[i].taskType + '"></span></td>'
                                + '<td class="selector text-align-center">' + json[i].currentFireTime + '</td>'
                                + '<td class="selector text-align-center">' + json[i].currentFinishTime + '</td>'
                                + '<td class="selector text-align-center">' + json[i].nextFireTime + '</td>'
                                + '<td class="selector text-align-center"><span class="badge-text badge-text-small translate status ' + json[i].statusLevel + '" translateFor="taskStatus" translateValue="' + status + '"></span></td>'
                                + '<td class="text-align-center"><button type="button" class="switch switch-style-2 search-task-switch-btn ' + (json[i].taskSwitch == 'O' ? 'switch-checked' : 'switch-checked-Unselected') + '"><span class="switch-inner translate lang" translateFor="taskSwitch" translateValue="' + json[i].taskSwitch + '"></span></button></td>'
                                + '<td class="td-actions text-align-center">'
                                + '<a href="javascript:void(0)" class="translate" translateFor="text.' + pauseAction + 'Task" translateTo="popoverTitle" action="' + pauseAction + 'Task"><i class="la la-' + pauseAction + ' edit"></i></a>'
                                + '<a href="javascript:void(0)" class="translate" translateFor="text.showTaskDetail" translateTo="popoverTitle" action="showTaskDetail"><i class="la la-edit edit"></i></a>'
                                + '<a href="javascript:void(0)" class="translate" translateFor="text.showSubTask" translateTo="popoverTitle" action="showSubTask"><i class="la la-external-link more"></i></a>'
                                + '<a href="javascript:void(0)" class="translate" translateFor="text.removeTask" translateTo="popoverTitle" action="deleteTask"><i class="la la-trash  delete"></i></a>'
                                + '</td></tr>';
                        }
                    }
                }
                if (options != undefined && (options.autoRefresh == true || options.singleRefresh == true)) {
                    tbody.find('a').unbind('mouseenter').unbind('mouseleave').each(function () {
                        hidePopoverByNode($(this));
                    });
                    saveOldParamAndDestroyDataTable(tbody);
                }
                removeTextEllipsis(tbody);
                tbody.html(tbodyHtml);
                tbody.find('.search-task-switch-btn').off('click').on('click', function (event) {
                    event.preventDefault();
                    event.stopPropagation();
                    page.changeTaskSwitch($(this));
                });
                createSearchTableBody(tbody, {
                    ordering: true,
                    columnDefs: [{
                        'targets': [0, 2, 3, 7, 8, 9],
                        'orderable': false
                    }]
                });
                textEllipsis(tbody, false);
                if (options === undefined) {
                    getPageData() && page.dataTable.search(getPageData()).draw(false);
                } else if (options.autoRefresh == true || options.singleRefresh == true) {
                    loadOldParamDataTable(tbody);
                    if (options.singleRefresh == true) {
                        var notyId = generateID('singleRefresh');
                        if (options.noty !== false) {
                            new Noty({
                                id: notyId,
                                type: 'success',
                                layout: 'bottomRight',
                                text: '<span class="translate" translateFor="message.singleRefreshSuccess"></span>',
                                progressBar: true,
                                timeout: 1500,
                                animation: {open: 'animated bounceInRight', close: 'animated bounceOutRight'}
                            }).show();
                        }
                        options['singleRefresh'] = false;
                    }
                    if (options.autoRefresh == true) {
                        var autoRefreshInterval = options.autoRefreshInterval || 5000;
                        setPageTimeout(function () {
                            page.createOrRefreshTaskTableBody(options);
                        }, autoRefreshInterval);
                        tbody.data('autoRefreshInterval', autoRefreshInterval);
                    }
                }
            }
        });
    };

    page.changeTaskSwitch = function (taskSwitchBtn) {
        var id = taskSwitchBtn.parents("tr").find('input[name="id"]').val();
        var taskId = taskSwitchBtn.parents("tr").find('.taskId').text();
        var taskSwitch = taskSwitchBtn.hasClass("switch-checked") ? 'C' : 'O';
        var confirmParams = {
            title: "modal.title.taskAction",
            okFun: function () {
                taskSwitchBtn.addClass('switch-loading');
                axiosPost({
                    url: "/schedule/task/changeTaskSwitch/" + id + "/" + taskSwitch,
                    success: function () {
                        var currentTd = taskSwitchBtn.parents('td');
                        var currentCell = page.dataTable.cell(currentTd);
                        var currentData = currentCell.data();
                        var translateValueClose = getTranslateValueByFor('taskSwitch.C');
                        var translateValueOpen = getTranslateValueByFor('taskSwitch.O');
                        if (taskSwitch == 'C') {
                            currentData = currentData.replace('translatevalue="O"', 'translatevalue="C"').replace(translateValueOpen, translateValueClose).replace('switch-checked', 'switch-checked-Unselected');
                        } else {
                            currentData = currentData.replace('translatevalue="C"', 'translatevalue="O"').replace(translateValueClose, translateValueOpen).replace('switch-checked-Unselected', 'switch-checked');
                        }
                        currentCell.data(currentData).draw(false);
                        currentTd.find('button').on('click', function () {
                            page.changeTaskSwitch($(this));
                        });
                    },
                    error: function (data) {
                        taskSwitchBtn.removeClass('switch-loading');
                    }
                });
            }
        };
        if (taskSwitch == 'C') {
            confirmParams['titleReplace'] = ["modal.close", cdata(taskId)];
            confirmParams['content'] = "modal.warn.taskSwitchContent";
        } else {
            confirmParams['titleReplace'] = ["modal.open", cdata(taskId)];
        }
        newConfirmModal(confirmParams);
    };

    page.batchChangeTaskSwitch = function (isOpen) {
        var checkedIds = getCheckedId();
        if (checkedIds && checkedIds.length > 0) {
            var checkedTaskIdStr = '', checkedIdStr = '', taskSwitchArray = [];
            var flag = false;
            $.each(checkedIds, function (i, item) {
                var tr = $('#checkbox-' + item).parents('tr');
                var taskIdSpan = tr.find('.taskId');
                var taskSwitch = tr.find('.search-task-switch-btn');
                if (taskIdSpan.length == 0 || taskSwitch.length  == 0) {
                    showErrorNoty({translateFor: "message.invalidData"});
                    flag = true;
                    return false;
                }
                checkedIdStr = checkedIdStr + item + ',';
                checkedTaskIdStr = checkedTaskIdStr + taskIdSpan.text() + ', ';
                taskSwitchArray.push(taskSwitch);
            });
            if (flag) {
                return;
            }
            checkedIdStr = checkedIdStr.substr(0, checkedIdStr.length - 1);
            checkedTaskIdStr = checkedTaskIdStr.substr(0, checkedTaskIdStr.length - 2);
            var taskSwitch = isOpen ? 'O' : 'C';
            var confirmParams = {
                title: "modal.title.taskAction",
                okFun: function () {
                    $.each(taskSwitchArray, function (i, item) {
                        item.addClass('switch-loading');
                    });
                    axiosPost({
                        url: "/schedule/task/changeTaskSwitch/" + checkedIdStr + "/" + taskSwitch,
                        success: function () {
                            $.each(taskSwitchArray, function (i, item) {
                                var currTaskSwitch = !item.hasClass("switch-checked") ? 'C' : 'O';
                                if (currTaskSwitch == taskSwitch) {
                                    item.removeClass('switch-loading');
                                    return true;
                                }
                                var currentTd = item.parents('td');
                                var currentCell = page.dataTable.cell(currentTd);
                                var currentData = currentCell.data();
                                var translateValueClose = getTranslateValueByFor('taskSwitch.C');
                                var translateValueOpen = getTranslateValueByFor('taskSwitch.O');
                                if (taskSwitch == 'C') {
                                    currentData = currentData.replace('translatevalue="O"', 'translatevalue="C"').replace(translateValueOpen, translateValueClose).replace('switch-checked', 'switch-checked-Unselected');
                                } else {
                                    currentData = currentData.replace('translatevalue="C"', 'translatevalue="O"').replace(translateValueClose, translateValueOpen).replace('switch-checked-Unselected', 'switch-checked');
                                }
                                currentCell.data(currentData).draw(false);
                                currentTd.find('button').on('click', function () {
                                    page.changeTaskSwitch($(this));
                                });
                            });
                        },
                        error: function (data) {
                            $.each(taskSwitchArray, function (i, item) {
                                item.removeClass('switch-loading');
                            });
                        }
                    });
                }
            };
            if (taskSwitch == 'C') {
                confirmParams['titleReplace'] = ["modal.close", cdata(checkedTaskIdStr)];
                confirmParams['content'] = "modal.warn.taskSwitchContent";
            } else {
                confirmParams['titleReplace'] = ["modal.open", cdata(checkedTaskIdStr)];
            }
            newConfirmModal(confirmParams);
        }
    };

    page.changeAllTaskSwitch = function (isOpen) {
        var taskSwitch = isOpen ? 'O' : 'C';
        var confirmParams = {
            title: "modal.title.allTaskSwitchAction",
            okFun: function () {
                $('.search-task-switch-btn').addClass('switch-loading');
                axiosPost({
                    url: "/schedule/task/changeAllTaskSwitch/" + taskSwitch,
                    success: function () {
                        page.createOrRefreshTaskTableBody({singleRefresh: true, noty: false})
                    },
                    error: function (data) {
                        $('.search-task-switch-btn').removeClass('switch-loading');
                    }
                });
            }
        };
        if (taskSwitch == 'C') {
            confirmParams['titleReplace'] = "modal.close";
            confirmParams['content'] = "modal.warn.taskSwitchContent";
        } else {
            confirmParams['titleReplace'] = "modal.open";
        }
        newConfirmModal(confirmParams);
    };

    page.showTaskDetail = function (node) {
        var tr = node.parents("tr");
        var id = tr.find('input[name="id"]').val();
        var taskId = tr.find('.taskId').text();
        newNormalModal({
            title: 'modal.title.showTaskDetail',
            titleReplace: cdata(taskId),
            showFooter: false,
            url: "/webjars/html/schedule/show-task-detail.htm",
            executeJs: "/webjars/js/schedule/show-task-detail.js",
            data: id,
            modalId: 'showTaskDetail',
            hideFun: function() {page.createOrRefreshTaskTableBody({singleRefresh: true, noty: false})}
        });
    };

    page.showSubTask = function (node) {
        var tr = node.parents("tr");
        var id = tr.find('input[name="id"]').val();
        var taskId = tr.find('.taskId').text();
        newNormalModal({
            title: 'modal.title.showSubTask',
            titleReplace: cdata(taskId),
            showFooter: false,
            executeJs: "/webjars/js/schedule/show-sub-task.js",
            data: id,
            modalId: 'showSubTask',
            hideFun: function() {page.createOrRefreshTaskTableBody({singleRefresh: true, noty: false})}
        });
    };

    page.playTask = function playTask(node) {
        alert('暂不可用')
    };

    page.pauseTask = function pauseTask(node) {
        alert('暂不可用')
    };

    page.deleteTask = function (node) {
        var tr = node.parents("tr");
        var status = tr.find('.status').attr('translateValue');
        if (status == 'B' || status == 'RB' || status == 'R' || status == 'RR' || status == 'P' || status == 'RP') {
            showErrorNoty({translateFor: "message.disallowedDeleteTask"});
            return;
        }
        var id = tr.find('input[name="id"]').val();
        var taskId = tr.find('.taskId').text();
        var confirmParams = {
            title: "modal.title.taskAction",
            titleReplace: ["modal.delete", cdata(taskId)],
            content: "modal.warn.deleteTaskContent",
            okFun: function () {
                axiosPost({
                    url: "/schedule/task/deleteTask/" + id,
                    success: function (json) {
                        setTimeout(function () {
                            if (json.status === 'success') {
                                showSuccessNoty({translateFor: json.msgCode});
                            } else {
                                showErrorNoty({translateFor: json.msgCode});
                            }
                            if (json.status == 'success') {
                                page.dataTable.rows(tr).remove().draw(false);
                                var checkedIds = getCheckedId();
                                if (checkedIds && checkedIds.length > 0) {
                                    checkedIds.remove(id);
                                    judgeCheckedId(checkedIds);
                                }
                            }
                        }, 500);
                    }
                });
            }
        };
        newConfirmModal(confirmParams);
    };

    page.batchDeleteTask = function () {
        var checkedIds = getCheckedId();
        if (checkedIds && checkedIds.length > 0) {
            var checkedTaskIdStr = '', checkedIdStr = '', invalidCheckedTaskIdStr = '', checkedTrArray = [];
            var flag = false;
            $.each(checkedIds, function (i, item) {
                var tr = $('#checkbox-' + item).parents('tr');
                var taskIdSpan = tr.find('.taskId');
                if (taskIdSpan.length == 0) {
                    showErrorNoty({translateFor: "message.invalidData"});
                    flag = true;
                    return false;
                }
                var status = tr.find('.status').attr('translateValue');
                if (status == 'B' || status == 'RB' || status == 'R' || status == 'RR' || status == 'P' || status == 'RP') {
                    invalidCheckedTaskIdStr = invalidCheckedTaskIdStr + taskIdSpan.text() + ', ';
                } else {
                    checkedIdStr = checkedIdStr + item + ',';
                    checkedTaskIdStr = checkedTaskIdStr + taskIdSpan.text() + ', ';
                    checkedTrArray.push({id: item, tr: tr});
                }
            });
            if (flag) {
                return;
            }
            if (checkedIdStr == '') {
                showErrorNoty({translateFor: "message.allTaskDisallowedDelete"});
                return;
            }
            checkedIdStr = checkedIdStr.substr(0, checkedIdStr.length - 1);
            checkedTaskIdStr = checkedTaskIdStr.substr(0, checkedTaskIdStr.length - 2);
            var confirmParams;
            var deleteConfirmFun = function () {
                confirmParams = {
                    title: "modal.title.taskAction",
                    titleReplace: ["modal.delete", cdata(checkedTaskIdStr)],
                    content: "modal.warn.deleteTaskContent",
                    okFun: function () {
                        axiosPost({
                            url: "/schedule/task/deleteTask/" + checkedIdStr,
                            success: function (json) {
                                setTimeout(function () {
                                    if (json.status === 'success') {
                                        showSuccessNoty({translateFor: json.msgCode});
                                    } else {
                                        showErrorNoty({translateFor: json.msgCode});
                                    }
                                    if (json.status == 'success') {
                                        var dataTable = page.dataTable;
                                        $.each(checkedTrArray, function (i, item) {
                                            dataTable.rows(item.tr).remove();
                                            checkedIds.remove(item.id);
                                        });
                                        dataTable.draw(false);
                                        judgeCheckedId(checkedIds);
                                    }
                                }, 500);
                            }
                        });
                    }
                };
                newConfirmModal(confirmParams);
            };
            if (invalidCheckedTaskIdStr != '') {
                invalidCheckedTaskIdStr = invalidCheckedTaskIdStr.substr(0, invalidCheckedTaskIdStr.length - 2);
                confirmParams = {
                    title: "modal.title.invalidDeleteTask",
                    titleReplace: cdata(invalidCheckedTaskIdStr),
                    okFun: function () {
                        deleteConfirmFun();
                    }
                };
                newConfirmModal(confirmParams);
            } else {
                deleteConfirmFun();
            }
        }
    };

    createSearchPage($("#content"), {
        createContentHeader: function (contentHeader, batchBtns, rightBtns) {
            contentHeader.append($('<button class="btn btn-gradient-04-left min-width-100" type="button"><span class="translate" translateFor="btn.openAutoRefresh"></span></button>').on('click', function () {
                    var $this = $(this);
                    var selectedBtn = $this.next();
                    var intervalBtn = selectedBtn.next();
                    page.createOrRefreshTaskTableBody({
                        autoRefresh: true,
                        autoRefreshInterval: intervalBtn.find('.autoRefreshInterval').text() * 1000
                    });
                    intervalBtn.addClass('selected');
                    $this.hide();
                    selectedBtn.show();
                }))
                .append($('<button class="btn btn-gradient-04-left min-width-100 selected" type="button"><span class="translate" translateFor="btn.closeAutoRefresh"></span></button>').on('click', function () {
                    var $this = $(this);
                    var unselectedBtn = $this.prev();
                    var intervalBtn = $this.next();
                    clearPageTimeout();
                    intervalBtn.removeClass('selected');
                    $this.hide();
                    unselectedBtn.show();
                }).hide())
                .append($('<button class="btn btn-gradient-04-right min-width-50" type="button"><span class="autoRefreshInterval">3</span><span class="translate unit" translateFor="timeUnit.second"></span></button>').on('click', function () {
                    var $this = $(this);
                    if ($this.data('btnSelected')) {
                        hidePopoverByNode($this);
                        return;
                    }
                    var slider = createSlider({
                        min: 1,
                        max: 10,
                        defaultValue: $this.find('.autoRefreshInterval').text(),
                        unit: $this.find('.unit').text(),
                        background: 'linear-gradient(to right,#54e38e 0%,#41c7af 50%,#54e38e 100%)'
                    });
                    showPopover($this, {
                        direction: 'top',
                        bodyStyle: 'width:250px;height:50px;margin:0px 6px 15px;',
                        bodyContent: slider,
                        animate: 'slide',
                        animateTime: 300,
                        leftOffset: -4,
                        scrollLock: true,
                        hideFun: function () {
                            $this.data('btnSelected', false);
                            var sliderValue = getSliderValue(slider);
                            getSliderValue(slider) && $this.find('.autoRefreshInterval').text(sliderValue);
                            if ($this.hasClass('selected')) {
                                clearPageTimeout();
                                page.createOrRefreshTaskTableBody({autoRefresh: true, autoRefreshInterval: sliderValue * 1000});
                            }
                        }
                    });
                    $this.data('btnSelected', true);
                }));
            batchBtns.append($('<button class="btn btn-gradient-04-left min-width-100" type="button"><span class="translate" translateFor="btn.batchOpenTaskSwitch"></span></button>').on('click', function(){page.batchChangeTaskSwitch(true)}))
                .append($('<button class="btn btn-gradient-04-center min-width-100" type="button"><span class="translate" translateFor="btn.batchCloseTaskSwitch"></span></button>').on('click', function(){page.batchChangeTaskSwitch(false)}))
                .append($('<button class="btn btn-gradient-04-right min-width-100" type="button"><span class="translate" translateFor="btn.batchDeleteTaskSwitch"></span></button>').on('click', function(){page.batchDeleteTask()}));
            rightBtns.append($('<div class="iconBtn translate float-right" translateFor="text.singleRefresh" translateTo="popoverTitle" ><i class="ti ti-reload"></i></div>').on('click', function(){page.createOrRefreshTaskTableBody({singleRefresh: true})}))
                .append($('<div class="iconBtn translate float-right mr-2" translateFor="text.closeAllTask" translateTo="popoverTitle" ><i class="ti ti-close"></i></div>').on('click', function(){page.changeAllTaskSwitch(false)}))
                .append($('<div class="iconBtn translate float-right mr-2" translateFor="text.openAllTask" translateTo="popoverTitle" ><i class="ti ti-check-box"></i></div>').on('click', function(){page.changeAllTaskSwitch(true)}))
                .append($('<div class="iconBtn translate float-right mr-2" translateFor="text.undoSelect" translateTo="popoverTitle" id="undoSelect"><i class="ti ti-back-left"></i></div>').on('click', function () {
                    getPageContext('checkedIds').length > 0 && $(page.dataTable.table().node()).find('tbody').find('tr.selected').find('label.click').click() && batchBtns.hide() && $(this).hide() && pushPageContext('checkedIds', []);
                }).hide());
        },
        createTableHead: function (theadTr) {
            theadTr.append($('<th style="min-width:9.3rem;border-left:0"><span class="translate" translateFor="label.taskId"></span></th>'))
                .append($('<th style="min-width:13.1rem;" class="text-align-center"><span class="translate" translateFor="label.taskName"></span></th>'))
                .append($('<th style="min-width:7.8rem;"><span class="translate" translateFor="label.taskType1"></span><i class="la la-filter filter"></i></th>'))
                .append($('<th style="min-width:9.3rem"><span class="translate" translateFor="label.currentFireTime"></span></th>'))
                .append($('<th style="min-width:9.3rem"><span class="translate" translateFor="label.currentFinishTime"></span></th>'))
                .append($('<th style="min-width:9.3rem"><span class="translate" translateFor="label.nextFireTime"></span></th>'))
                .append($('<th style="min-width:8.6rem"><span class="translate" translateFor="label.status"></span><i class="la la-filter filter"></i></th>'))
                .append($('<th style="min-width:7.5rem"><span class="translate" translateFor="label.taskSwitch1"></span><i class="la la-filter filter"></i></th>'))
                .append($('<th style="min-width:9.3rem;border-right:0" class="text-align-center"><span class="translate" translateFor="label.actions"></span></th>'));
        },
        createTableBody: function (tbody) {
            pushPageContext('tbody', tbody);
            page.createOrRefreshTaskTableBody();
        }
    });
})(jQuery);